<?php
namespace App\Controllers\Coupons;
use App\Models\Goods\Goods;
use App\Models\Store\Store;
use App\Libs\Coupons\Couponslib;
/**
*	获取可用与不可用优惠券信息
*/
class getCouponsZone extends \App\Libs\Base\BaseAction
{
	protected function beforeRun() {
         parent::beforeRun();
         $this->needLogin = TRUE;
    }
	
	public function execute() {
		$user = $this->session->user;
		$gid = (int)$this->request->get("gid");//商品id
		$gsum = (int)$this->request->get("gsum");//商品数量
		if( empty($gid) ){
			return \App\Libs\Views\Json::view( 1 , '商品不能为空', null);
		}
		if( $gsum < 1 ){
			return \App\Libs\Views\Json::view( 1 , '商品数量不能为空', null);	
		}
		//商品验证及获取
		$goodsInfo = Goods::find(array(
			' id = :gid: ',
			'bind'=>array('gid'=>$gid)
		));
		if( !empty( $goodsInfo ) ){
			$goodsInfo = $goodsInfo->toArray();
		}else{
			return \App\Libs\Views\Json::view( 1 , '商品不能为空', null);	
		}
		
		//获取店铺
		$storeInfo = Store::find(array(
			' id = :sid: ',
			'bind'=>array('sid'=>$goodsInfo['sid'])
		));
		if( !empty( $storeInfo ) ){
			$storeInfo = $storeInfo->toArray();
		}else{
			return \App\Libs\Views\Json::view( 1 , '商品所属店铺不能为空', null);	
		}
		
		//查询优惠券
		$couponsList = Couponslib::getCouponsZone( $user->id );
		$result = ['usable'=>[],'nousable'=>[]];
		if( !empty( $couponsList ) ){
			$goodsTotalPrice = ($goodsInfo['sale_price'] * $gsum);//商品总金额
			foreach( $couponsList as $k=>$v ){
				//区分哪些是可用哪些不可用
				$v['start_time'] = date("Y/m/d",strtotime($v['start_time']));
				$v['end_time'] = date("Y/m/d",strtotime($v['end_time']));
				if( ($v['type'] == $storeInfo['store_type'] || $v['type'] == 0) &&  $v['full_price'] <= $goodsTotalPrice && $v['status'] == '0' ){
					$result['usable'][] =  $v;
				}else{
					$result['nousable'][] = $v;	
				}
			}
			//返回成功数据
			return \App\Libs\Views\Json::view( 0 , '成功', $result);
		}else{
			//返回成功数据
			return \App\Libs\Views\Json::view( 0 , '成功', $result);
		}
		
		
	}
}
